#!/usr/bin/python
# -*- coding:utf-8 -*-
# @FileName : DL4_test2.py
# Author    : myh

import torch
from torch import nn
from d2l import torch as d2l


def relu(X):
    a = torch.zeros_like(X)
    return torch.max(X, a)


def softmax(X):
    X_exp = torch.exp(X)
    # 维度0：对每一列求和    维度1：对每一行求和
    X_sum = X_exp.sum(1, keepdim=True)
    return X_exp / X_sum

def net(X):
    X = X.reshape((-1, num_inputs))
    H = relu(X@W1 + b1)  # 这里“@”代表矩阵乘法
    H1 = relu(H@W2 + b2)
    return (H1@W3 + b3)


if __name__ == '__main__':
    # 数据采集步长
    batch_size = 256
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

    num_inputs, num_outputs, num_hiddens = 784, 10, 256

    # 每一层都要记录参数
    W1 = nn.Parameter(torch.randn(
        num_inputs, num_hiddens, requires_grad=True) * 0.01)
    b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
    W2 = nn.Parameter(torch.randn(
        num_hiddens, num_hiddens, requires_grad=True) * 0.01)
    b2 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
    W3 = nn.Parameter(torch.randn(
        num_hiddens, num_outputs, requires_grad=True) * 0.01)
    b3 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))

    params = [W1, b1, W2, b2, W3, b3]
    # 损失函数
    loss = nn.CrossEntropyLoss(reduction='none')

    num_epochs, lr = 10, 0.3
    updater = torch.optim.SGD(params, lr=lr)
    d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
    d2l.plt.show()

    d2l.predict_ch3(net, test_iter)
